import java.util.concurrent.CountDownLatch;

//CountDownLatch 类位于 java.util.concurrent 包下，利用它可以实现类似计数器的功能。比如有
// 一个任务 A，它要等待其他 4 个任务执行完毕之后才能执行，此时就可以利用 CountDownLatch
// 来实现这种功能了。
public class CountDownLatchDemo {

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        Thread thread1 = new Thread(){
            @Override
            public void run() {
                System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("子线程"+Thread.currentThread().getName()+"执行结束");
                countDownLatch.countDown();
            }
        };
        thread1.start();
        Thread thread2 = new Thread(){
            @Override
            public void run() {
                System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("子线程"+Thread.currentThread().getName()+"执行结束");
                countDownLatch.countDown();
            }
        };
        thread2.start();

        System.out.println("等待执行完成......");
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("执行结束，执行main");

    }
}
